package com.learn.authentication.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.learn.authentication.mapper.UserMapper;
import com.learn.authentication.pojo.LogUser;
import com.learn.authentication.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/04/06
 * @description 自定义的UserDetailsService实现类
 * 自定义自己的查询用户方法
 * 记得注册到IoC容器中
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // mp通过用户名查询数据库的用户信息
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(lambdaQueryWrapper);
        // TODO 这里可以补充全局异常处理
        if(Objects.isNull(user)) {
            throw new RuntimeException("用户名不存在");
        }
        // TODO 接下来还需要添加权限信息
        // Set.of()，但是听说set建好后不可变,不能add
        // new HashSet<>(Arrays.asList()) 可变
        // 到这里就需要返回UserDetails对象，他也是个接口，需要自己写实现类
        return new LogUser(user, new HashSet<>(Set.of("test", "admin")));
    }
}
